<?php
// +----------------------------------------------------------------------
// | OneThink [ WE CAN DO IT JUST THINK IT ]
// +----------------------------------------------------------------------
// | Copyright (c) 2013 http://www.onethink.cn All rights reserved.
// +----------------------------------------------------------------------
// | Author: 麦当苗儿 <zuojiazi@vip.qq.com> <http://www.zjzit.cn>
// +----------------------------------------------------------------------

namespace Admin\Controller;
use Think\Page;

/**
 * 后台用户控制器
 * @author 麦当苗儿 <zuojiazi@vip.qq.com>
 */
class  GoodsController extends AdminController {


	public function index(){
		
		$p = !empty($_GET["p"]) ? $_GET['p'] : 1;
		$brand_id = !empty($_GET["bid"]) ? $_GET['bid'] : 0;
		
		if(empty($brand_id)){
			
			 $this->error('数据错误！');
			 
		}
		
		$map = array();
		$map['brand_id'] = $brand_id;
		$user_object   = D('Goods');
        $data_list     = $user_object
            ->page($p, C('ADMIN_PAGE_ROWS'))
            ->where($map)
            ->order('id desc')
            ->select();
			
        $page = new Page($user_object->where($map)->count(),C('ADMIN_PAGE_ROWS'));
	
	    $show = $page->show();// 分页显示输出
	
	    /*当前品牌名称*/
		$map2 = array();
		$map2['id'] = $brand_id;
		$infos =M('admin_brand')->where($map2)->find();//查询数据
		$this->assign('brand_name',$infos['brand_name']);// 赋值输出
	
	    $this->assign('data_list',$data_list);// 赋值输出
	    $this->assign('page',$show);// 赋值分页输出
	    $this->assign('brand_id',$brand_id);// 赋值分页输出
		
		$this->display();
		
	}
	
	/*导入*/
	public function import()
    {   
	   /*品牌ID*/
	   $brand_id = !empty($_POST["brand_id"]) ? $_POST['brand_id'] : 0;
	   
	   if(empty($brand_id)){ 
		 $this->error("数据错误!");
		 exit; 
	   }
	   
       /*接受导入Excel导入数据*/
		if ($_FILES['user_file']['name'] && $_FILES['user_file']['name'] != 'none') {
			
			/*获取文件后缀名*/
			$ext = strrchr($_FILES['user_file']['name'], '.');

			if ($ext != '.xlsx' && $ext != '.xls') {
				$this->error("上传文件格式不正确!");
				exit;
			}
			
			
			$file_url = $this->upfileok();//文件上传方法！
			
			/*上传文件存放目录*/
			$filename = 'Uploads/' . $file_url;
			
			set_time_limit(0);
			@ini_set('memory_limit', '1024M');//设置PHP能使用的内存大小
			//导入PHPExcel类库
			import("Org.Util.PHPExcel");
			
			//创建PHPExcel对象，注意，不能少了\
			$PHPExcel=new \PHPExcel();
			
			//如果excel文件后缀名为.xlsx，导入这下类
			import("Org.Util.PHPExcel.Reader.Excel2007");
			$PHPReader=new \PHPExcel_Reader_Excel2007();
			
			//获取文件读取操作对象
			$objPHPExcel = $PHPReader->load($filename);            //加载文件
			
			$i = 0;
			
			/* 	print_r($objPHPExcel->getWorksheetIterator());
			die(); */
			
			foreach ($objPHPExcel->getWorksheetIterator() as $sheet) {
				    
					/*数据库处理数组*/
					$datas = array();

					if($i == 0){
						/*商品数据*/
						$data0 = array('goods_name','goods_type_memory','goods_type_colour','shop_price');
						
					}else{
						
						/*多出的sheet不再处理 跳出循环*/
						break;
					}
					

					//逐行处理
					$y = 0;
				    foreach ($sheet->getRowIterator() as $row) {
						
					      /*跳过第一行 不需要可以注释*/
						  if ($row->getRowIndex() < 2) {
								continue;
							}
					
					      /*逐列读取*/
						  $cellIterator = $row->getCellIterator();
						  
						  /*遇空单元格不跳过*/
						  $cellIterator->setIterateOnlyExistingCells(false);
					      
						  $k = 0;
						  foreach ($cellIterator as $cell) {//逐列读取
							
							$data = $cell->getValue();
					
							/*数据处理*/
							$datas[$y][$data0[$k]] = $data;
							
							$k++;

						  }
						$y++;						  
					}

					
					if(empty($datas)){
						$this->error("导入失败,请重新导入!");
						exit;
					}
					// echo "<pre>";
					// print_r($datas);
					// echo "</pre>";
					// die;array('goods_name','goods_type_memory','goods_type_colour','shop_price');
						
					/*数据处理 写入数据库   开始*/
					foreach($datas as $k=>$value){
						
						if(empty($value['goods_name']) && empty($value['goods_type_memory']) && empty($value['goods_type_colour'])  && empty($value['shop_price']) ){
						  	
							continue;// 当 $value为空时，跳出本次循环 
							
						}
					   /*数据处理方法 $arry数据*/
					   D("Goods")->set_sql_excel($brand_id,$value);

					}
					
					
					
					/*数据处理 写入数据库   结束*/
				
					
	          $i++;
			}

			
			$this->success("导入成功!");
			exit;
			
		   
		}else{
		
          $this->error("请选择要导入的文件!");

		}
		 
    }
	

	/*编辑*/
	public function edit($id)
    {
		
		
        if (IS_POST) {
    
            // 提交数据

			$user_object = D('Goods');	
			
            $data  = $user_object->create();
			
			$data['add_time'] = time();
			
			$time = $data['add_time'];
			
			if(empty($data['goods_name'])){	
					$this->error("请输入商品信息！");
					 exit;
				 }
			if(empty($data['goods_type_memory'])){	
					$this->error("请输入商品属性！");
					 exit;
				 }	 
			if(empty($data['goods_type_memory'])||empty($data['goods_type_colour'])){	
					$this->error("请输入商品属性！");
					 exit;
				 }
			if(empty($data['shop_price'])){	
					$this->error("请输入商品价格！");
					 exit;
				 }
			
		
            if ($data) {
				
				$sql = M('admin_goods')->where(array("id"=>$data['id']))->field('brand_id')->find();
				
				$brand_id = $sql['brand_id'];
				
				$data['brand_id'] = $brand_id;
				
				unset($data['add_time']);
					
				$sql2 = M('admin_goods')->where(array("id"=>$data['id']))->field('id,brand_id,goods_name,goods_type_memory,goods_type_colour,shop_price')->find();
					

	
			if($data == $sql2){
				
					$data['add_time'] = $time;
				
					$result = $user_object
							->field('id,goods_name,goods_type_memory,goods_type_colour,shop_price,add_time')
							->save($data);

					$this->success('更新成功', U('index',array('bid'=>$_POST['bid'])));
				
			}else{	
				
				$data['add_time'] = $time;
				
				$count = M("admin_goods")->where(array("brand_id"=>$brand_id,"goods_name"=>$data['goods_name']))->count();	
				
				if($count > 0){
				/*判断内存*/		
				   $count1 = M("admin_goods")->where(array("brand_id"=>$brand_id,"goods_name"=>$data['goods_name'],"goods_type_memory"=>$data['goods_type_memory']))->count();
				   
				   if($count1 > 0){
					/*判断颜色*/  
					   $count2 = M("admin_goods")->where(array("brand_id"=>$brand_id,"goods_name"=>$data['goods_name'],"goods_type_memory"=>$data['goods_type_memory'],"goods_type_colour"=>$data['goods_type_colour']))->count();
					   
						if($count2 > 0){
						   
						   $count3 = M("admin_goods")->where(array("brand_id"=>$brand_id,"goods_name"=>$data['goods_name'],"goods_type_memory"=>$data['goods_type_memory'],"goods_type_colour"=>$data['goods_type_colour'],"shop_price"=>$data['shop_price']))->count();
						   
							if($count3 == 0){
								
							   /*更新价格*/
								$where['brand_id'] = $brand_id;
								$where['goods_name'] = $data['goods_name'];
								$where['goods_type_memory'] = $data['goods_type_memory'];
								$where['goods_type_colour'] = $data['goods_type_colour'];
							    $where['id'] = $data['id'];
								$data2['shop_price'] = $data['shop_price'];
								$data2['add_time'] = time();
							   
								$ret = M("admin_goods")->where($where)->save($data2);
							
									if ($ret) {
										$this->success('更新成功', U('index',array('bid'=>$_POST['bid'])));
									}else{
											$this->error('更新失败', $user_object->getError());
									  }
								
							}else{
								$this->success('此条数据已存在,不做任何操作！', U('index',array('bid'=>$_POST['bid'])));
							}
						   
						}else{
						   
							$result = $user_object
							->field('brand_id,goods_name,goods_type_memory,goods_type_colour,shop_price,add_time')
							->add($data);
							
							  if ($result) {
									$this->success('添加成功', U('index',array('bid'=>$_POST['bid'])));
							  }else{
									$this->error('更新失败', $user_object->getError());
							  }						   
						}

				   }else{
					/*新增*/
					  $result = $user_object
							->field('brand_id,goods_name,goods_type_memory,goods_type_colour,shop_price,add_time')
							->add($data);
					  if ($result) {
							$this->success('添加成功', U('index',array('bid'=>$_POST['bid'])));
					  }else{
							$this->error('更新失败', $user_object->getError());
					  }
				   }
				   

				}else{
				/*不存在 添加*/	
				
					$result = $user_object
							->field('brand_id,goods_name,goods_type_memory,goods_type_colour,shop_price,add_time')
							->add($data);
							
					if ($result) {
							$this->success('添加成功', U('index',array('bid'=>$_POST['bid'])));
					}else{
							$this->error('添加失败', $user_object->getError());
					}
				}
			
			  }
			  
            } else {
				
                $this->error($user_object->getError());
            }
			
        } else {
			
            // 获取信息
		    $id = !empty($_GET["id"]) ? $_GET['id'] : 0;
			
			if(empty($id)){
				
				$this->error('数据错误！', $user_object->getError());
				
			}
			
            $info = D('Goods')->find($id); 
			$this->assign('info',$info);// 赋值分页输出

			$brands = M("admin_brand")->where("id='$info[brand_id]'")->find();
			
			$this->assign('brand_name',$brands['brand_name']);
		
			$this->display();
    
        }
    }

		
	//删除指定数据		
	public function delete(){
		
		// 提交数据
		$user_object = D('Goods');
		$id =$_GET['id'];
		
		if ($id) {
			
			$result = $user_object->shanchu();
			
			if ($result) {
				$this->success('删除成功');
			} else {
				$this->error('删除失败', $user_object->getError());
			}
			
		} else {
			$this->error($user_object->getError());
		}
	
	
	}
	
	
	
	
	   //文件上传
    public function upfileok() {

        $upload = new \Think\Upload(); // 实例化上传类
		
        $upload->maxSize = 3145728; // 设置附件上传大小
        $upload->exts = array('xlsx', 'xls'); // 设置附件上传类型
        $upload->rootPath = './Uploads/'; // 设置附件上传根目录
		
        // 上传单个文件 
        $info = $upload->uploadOne($_FILES['user_file']);
       // dump($info);
	   // die;

		 if (!$info) {// 上传错误提示错误信息
            $this->error($upload->getError());
			
        } else {// 上传成功 获取上传文件信息

            return $info['savepath'] . $info['savename'];
        }
		
		
    }
	
	
	
	
	

}